package com.yangchao.webflux.config;

import jakarta.annotation.Nullable;
import org.slf4j.Logger;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Component
public class MyWebFilter implements WebFilter {

    Logger log = org.slf4j.LoggerFactory.getLogger(MyWebFilter.class);
    @Override
    public Mono<Void> filter(@Nullable ServerWebExchange exchange, WebFilterChain chain) {
        assert exchange != null;
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        log.info("请求处理放行到目标方法之前...");
        Mono<Void> filter = chain.filter(exchange); // 放行
        // 流一旦经过某个操作就会变成新流
        Mono<Void> voidMono = filter.
                doOnSuccess(r -> {
                    log.info("doOnSuccess 目标方法执行以后...");
                })
                .doOnError(err -> {
                    log.info("doOnError 目标方法异常以后...");
                }) // 目标方法发生异常后做事
                .doFinally(signalType -> {
                    log.info("doFinally 目标方法执行以后...");
                });// 目标方法执行之后

        // 上面执行不花时间。
        return voidMono;
    }
}